import {messages} from "share/common";
import React from 'react';
import { connect } from 'react-redux'
import menuRoute from "routes/menuRoute";
import moment from 'moment';
import {Button, Select, Icon, message, Form, Input, Switch, Row, Col, Checkbox, TimePicker, Radio} from 'antd';
const Option = Select.Option;
const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;
const RadioGroup = Radio.Group;
import 'styles/setting/notification-setting/edit-notification-rule.scss'
import notificationRolesService from 'containers/setting/notification-setting/notification-setting.service'

class EditNotificationRules extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      data: [],
      record: {
        isEnabled: true,
        regulationName: '',
        regulationCode: '',
        triggerType: 'AUTO',
        regulationComment: '',
        remindClients: [],
        remindDays: [],
        remindTimes: [],
      },
      isNew: true,
      methods: [],
      localTimes: [],
    }
  }

  componentWillMount (){
    this.getNotificationRulesMethods();
  }

  componentWillReceiveProps(nextProps){
    if(nextProps.params.showSlideFrame === this.props.params.showSlideFrame){
      return
    }else if(nextProps.params.showSlideFrame){
      let arr = [];
      nextProps.params.record.remindTimes.map(item => {
        arr.push(item)
      });
      this.setState({
        localTimes: arr,
        record: nextProps.params.record,
        isNew: nextProps.params.isNew,
      }, () => {
        this.props.form.setFieldsValue(this.state.record)
      })
    }
  }

  getNotificationRulesMethods = () => {
    const {methods} = this.state;
    notificationRolesService.getNotificationRulesMethods().then(res => {
      res.data.map(item => {
        methods.push({label: item.messageKey, value: item.value})
      });
      this.setState({
        methods,
      });
    }).catch(err => {

    })
  };

  handleSave = () => {
    const {record, localTimes} = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if(!err){
        let item =Object.assign(record, values);
        if(values.triggerType === "AUTO"){
          if(localTimes.length){
            if(new Set(localTimes).size !== localTimes.length){
              message.error(messages('setting.key1650')/*提醒时间不能重复*/);
            }else{
              let arr = [];
              localTimes.map(item => {
                arr.push(item)
              });
              item.remindTimes = arr;
              this.saveRecord(item);
            }
          }else{
            message.error(messages('setting.key1579')/*提醒时间不能为空*/)
          }
        }else{
          item.remindDays = [];
          item.remindTimes = [];
          this.saveRecord(item);
        }
      }
    });

  };

  saveRecord = (item) => {
    const {isNew} = this.state;
    this.setState({
      loading: true,
    });
    if(isNew){
      notificationRolesService.addNotificationRules(item).then(res => {
        this.setState({
          visible: false,
          loading: false,
        });
        this.props.close(true);
      }).catch(err => {
        this.setState({
          visible: false,
          loading: false,
        })
      })
    }else{
      notificationRolesService.editNotificationRules(item).then(res => {
        this.setState({
          visible: false,
          loading: false,
        });
        this.props.close(true);
      }).catch(err => {
        this.setState({
          visible: false,
          loading: false,
        })
      })
    }
  };


  onAddRemindTimes = () => {
    const {localTimes} = this.state;
    localTimes.push('08:00');
    this.setState({
      localTimes,
    })
  };

  onTimePickerChange = (value, index) => {
    const {localTimes} = this.state;
    let err = false;
    localTimes.map(item => {
      if(item === value){
        err = true;
      }
    });
    if(err){
      message.error('提醒时间不能重复');
    }else {
      localTimes[index] = value;
      this.setState({
        localTimes,
      })
    }
  };

  handleDelete = (index) => {
    const {localTimes} = this.state;
    localTimes.delete(localTimes[index]);
    this.setState({localTimes})
  };

  render () {
    const {loading, methods, record, localTimes} = this.state;
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 15 }
    };
    const specialFormItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 20 }
    };
    const options = [
      { label: messages('setting.key1567')/*每周一*/, value: 'MON' },
      { label: messages('setting.key1568')/*每周二*/, value: 'TUE' },
      { label: messages('setting.key1569')/*每周三*/, value: 'WED' },
      { label: messages('setting.key1570')/*每周四*/, value: 'THU' },
      { label: messages('setting.key1571')/*每周五*/, value: 'FRI' },
      { label: messages('setting.key1572')/*每周六*/, value: 'SAT' },
      { label: messages('setting.key1573')/*每周日*/, value: 'SUN' },
    ];
    const hourOptions = [
      {label: '00:00', value: '00:00'},
      {label: '01:00', value: '01:00'},
      {label: '02:00', value: '02:00'},
      {label: '03:00', value: '03:00'},
      {label: '04:00', value: '04:00'},
      {label: '05:00', value: '05:00'},
      {label: '06:00', value: '06:00'},
      {label: '07:00', value: '07:00'},
      {label: '08:00', value: '08:00'},
      {label: '09:00', value: '09:00'},
      {label: '10:00', value: '10:00'},
      {label: '11:00', value: '11:00'},
      {label: '12:00', value: '12:00'},
      {label: '13:00', value: '13:00'},
      {label: '14:00', value: '14:00'},
      {label: '15:00', value: '15:00'},
      {label: '16:00', value: '16:00'},
      {label: '17:00', value: '17:00'},
      {label: '18:00', value: '18:00'},
      {label: '19:00', value: '19:00'},
      {label: '20:00', value: '20:00'},
      {label: '21:00', value: '21:00'},
      {label: '22:00', value: '22:00'},
      {label: '23:00', value: '23:00'},
    ];
    return (
      <div className={'edit-notification-rules'}>
        <div style={{color: '#656565', fontWeight: 650, fontSize: 18, marginBottom: 50}}>{messages('setting.key1371')/*基础信息*/}</div>
        <Form>
          <FormItem {...formItemLayout} label={messages('setting.key1096')/*状态*/}>
            {getFieldDecorator('isEnabled', {
              valuePropName: 'checked',
              rules: [{
                required: true,
                message: messages('setting.key1580')/*请选择状态*/
              }]
            })
            (<Switch/>)
            }
          </FormItem>
          <FormItem label={messages('setting.key1581')/*规则编码*/} {...formItemLayout}>
            {getFieldDecorator('regulationCode',{
              rules: [{
                required: true,
                message: messages('setting.key1582')/*规则编码不能为空*/
              }]
            })
            (<Input placeholder={messages('common.please.input')/*请输入*/}/>)
            }
          </FormItem>
          <FormItem label={messages('setting.key1091')/*规则名称*/} {...formItemLayout}>
            {getFieldDecorator('regulationName',{
              rules: [{
                required: true,
                message: messages('setting.key1583')/*规则名称不能为空*/
              }]
            })
            (<Input placeholder={messages('common.please.input')/*请输入*/}/>)
            }
          </FormItem>
          <Form onSubmit={this.handleSubmit}>
            {/*员工是否可修改单价*/}
            <FormItem {...formItemLayout} label={messages('setting.key1703')/*规则类型*/}>
              {
                getFieldDecorator('triggerType', {
                  rules: [{
                    required: true,
                    message: messages('setting.key1704')/*规则类型不能为空*/
                  }]
                })(
                  <RadioGroup>
                    <Radio value='AUTO'>{messages('setting.key1705')/*满足条件后台自动触发*/}</Radio>
                    <Radio value='MANUAL'>{messages('setting.key1706')/*手动触发*/}</Radio>
                  </RadioGroup>
                )
              }
            </FormItem>
          </Form>
          <FormItem label={messages('setting.key1178')/*规则描述*/} {...formItemLayout}>
            {getFieldDecorator('regulationComment',{
              rules: [{
                required: true,
                message: messages('setting.key1584')/*规则描述不能为空*/
              }]
            })
            (<Input placeholder={messages('common.please.input')/*请输入*/}/>)
            }
          </FormItem>
          <FormItem label={messages('setting.key95')/*提醒方式*/} {...formItemLayout}>
            {getFieldDecorator('remindClients',{
              rules: [{
                required: true,
                message: messages('setting.key1585')/*提醒方式不能为空*/
              }]
            })
            (<CheckboxGroup options={methods} style={{paddingTop: 5}}/>)
            }
          </FormItem>
          {
            this.props.form.getFieldValue("triggerType") === "AUTO" &&
            <FormItem
              label={<span><span style={{color: 'red'}}>*</span>&nbsp;{messages('setting.key743')/*提醒时间*/}</span>}
              {...specialFormItemLayout}>
              {
                localTimes.length > 0 ?
                  localTimes.map((item, index) => {
                    return (
                      <span key={index}>
                     <Col key={index} span={5} style={{marginRight: 10}}>
                      <Select key={index}
                              size={'small'}
                              showSearch={true}
                              allowClear={false}
                              value={item}
                              onChange={(e) => {
                                this.onTimePickerChange(e, index)
                              }}
                              placeholder={messages('common.please.select')}
                              getPopupContainer={triggerNode => triggerNode.parentNode}
                              filterOption={(inputValue, option) => option.props.children.indexOf(inputValue) > -1}>
                        {hourOptions.map(item => {
                          return (
                            <Option key={item.value}>{item.value}</Option>
                          )
                        })}
                      </Select>
                   </Col>
                     <Col onClick={() => this.handleDelete(index)} span={2} style={{cursor: 'pointer'}}>
                       <Icon type="close-circle-o" style={{color: 'red', fontSize: 15}}/>
                     </Col>
                   </span>
                    )
                  })
                  :
                  null
              }
              <Col span={8}>
                <Button onClick={this.onAddRemindTimes} size={'small'} type="dashed">
                  <Icon type="plus"/>{messages('common.add')/*添加*/}
                </Button>
              </Col>
            </FormItem>
          }
          {
            this.props.form.getFieldValue("triggerType") === "AUTO" &&
            <FormItem label={messages('setting.key1574')/*重复提醒*/} {...formItemLayout}>
              {getFieldDecorator('remindDays', {
                initialValue: record.remindDays,
                rules: [{
                  required: true,
                  message: messages('setting.key1586')/*重复提醒不能为空*/
                }]
              })
              (<CheckboxGroup options={options} style={{paddingTop: 5}}/>)
              }
            </FormItem>
          }
      </Form>
        <Row >
          <Col span={1} offset={4}>
            <Button onClick={this.handleSave} type={'primary'} loading={loading}>{messages('setting.key1079')/*保存*/}</Button>
          </Col>
          <Col span={1} offset={3}>
            <Button onClick={() => {this.props.close(true)}}>{messages('setting.key1080')/*取消*/}</Button>
          </Col>
        </Row>
      </div>
    )
  }
}

EditNotificationRules.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
  }
}


const wrappedEditNotificationRules = Form.create()(EditNotificationRules);
export default connect(mapStateToProps)(wrappedEditNotificationRules);
